/*
 * @Author: ylyu
 * @Date: 2024-02-22 21:06:09
 * @LastEditors: ylyu
 * @LastEditTime: 2024-02-23 11:06:54
 * @Description: 主进程
 */
const { ipcMain, ipcRenderer, BrowserWindow, webContents } = require('electron')
const getSource = (url) => {
  return new Promise((resolve, reject) => {
    // 异步操作- 抓取页面
    const win = new BrowserWindow({
      width: 500,
      height: 500,
      show: false,
      webPreferences: {
        offscreen: true,
      },
    })
    win.loadURL(url)
    win.webContents.on('did-finish-load', async () => {
      const title = win.getTitle()
      console.log(title)
      try {
        // nativeImage
        const img = await win.webContents.capturePage() // 异步操作
        const screenshot = img.toDataURL()
        console.log(screenshot)
        resolve({ title, screenshot, url })
      } catch (error) {
        reject(error)
        console.log(error)
      }
    })
    // console.log(url)
    // return '收到信息'
  })
}

// 主进程接收到渲染进程传来的url，执行异步操作，将结果返回给渲染进程
ipcMain.handle('on-url-event', async (e, url) => {
  const res = await getSource(url)
  return res
})
module.exports = getSource
